package com.aliyun.solutions.demo.wanxiang.web;

import com.aliyun.solutions.demo.wanxiang.model.ApiResult;
import com.aliyun.solutions.demo.wanxiang.utils.ValidateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * 异常建议
 *
 * @author solution
 * @date 2024/12/04
 */
@Slf4j
@RestControllerAdvice
public class ControllerAdvice {

    @ExceptionHandler(Exception.class)
    ApiResult defaultHandler(Exception e) {
        log.error(e.getMessage(), e);
        if (e instanceof ConstraintViolationException) {
            ConstraintViolationException cve = (ConstraintViolationException)e;
            String message = ValidateUtils.buildExceptionMessage(cve);
            return ApiResult.fail(message);
        }
        return ApiResult.fail(e.getMessage());
    }

}